package cn.tedu._05mvcboot03.controller;

import cn.tedu._05mvcboot03.base.response.JsonResult;
import cn.tedu._05mvcboot03.base.response.StatusCode;
import cn.tedu._05mvcboot03.mapper.MVCUserMapper;
import cn.tedu._05mvcboot03.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot03.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot03.pojo.entity.MVCArticle;
import cn.tedu._05mvcboot03.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Validated
@RestController
@RequestMapping("/v1/users")
@Api(tags = "用户管理模块")
@Slf4j
public class MVCUserController {
    @Autowired
    private MVCUserMapper mvcUserMapper;

    @PostMapping("/login")
    @ApiOperation(value = "登录用户", notes = "登录用户")
    @ApiImplicitParam(name = "userLogin", value = "用户登录信息", required = true, dataType = "UserLoginDTO")
    public JsonResult login(@RequestBody UserLoginDTO userLogin, @ApiIgnore HttpSession session) {
        UserVO userVO = mvcUserMapper.select(userLogin.getUsername(), userLogin.getPassword());
        if (userVO == null) return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        session.setAttribute("user",userVO);
        return JsonResult.ok();
    }

    @PostMapping("/article")
    @ApiOperation(value = "发布文章", notes = "发布文章")
    @ApiImplicitParam(name = "userArticle", value = "用户文章信息", required = true, dataType = "UserArticleDTO")
    public JsonResult article(@Validated @RequestBody UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session) {
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO == null) return new JsonResult(StatusCode.NOT_LOGIN);
        MVCArticle mvcArticle = new MVCArticle();
        BeanUtils.copyProperties(userArticleDTO,mvcArticle);
        mvcArticle.setUserId(userVO.getId());
        mvcUserMapper.insertArticle(mvcArticle);
        return JsonResult.ok();
    }

    @GetMapping("/selectByArticleId")
    @ApiOperation(value = "根据文章id查询用户信息", notes = "根据文章id查询用户信息")
    @ApiImplicitParam(name = "articleId", value = "文章id", required = true, dataType = "Long")
    public JsonResult selectByArticleId(@Range(min = 1, max = 100, message = "文章id必须在1-100之间") @RequestParam Long articleId) {
        return JsonResult.ok(mvcUserMapper.selectByArticleId(articleId));
    }
}
